let machine = require ('../public/index.js');
const dao = require('./dao');
const iceCreamModel = new dao();
class iceCream extends machine {
    constructor(httpClient, tcpServe) {
        super(httpClient, tcpServe);
        this.connect();
        this.order = '';
        this.productId = '';
        this.storeId = '1176112658763165697';
        this.orderDetailId = '';
        this.date = '';
        this._mealId = '';
        //测试
        this.iceCreamIp = '::ffff:172.29.3.30';
    }
    connect() {
        this.tcpConnect((socket) => {
            console.log('设备连接...');
            let key = socket.remoteAddress;//每个用户的唯一标示
            console.log("设备ip:",key);
            // 将获取到client的数据写到数组，识别client是对应的ID是什么设备
            // 设备首次连接触发
            let times = (new Date()).getTime();
            // 设备状态
            this.clients[key] = {
                nickname:'100',
                socket: socket, // client端
                timestamp:times,
                isOpen: 1, // 是否启动
                workStatus: 1, // 工作状态
                deviceStatus: 1, // 设备状态
                intakeStatus: 1 //取餐口状态
            };  //初始化设备状态
            // 告诉云端设备该PLC已经上线
            this.clientConnected(socket);
            this.receiveScanData({orderId: '1206510557960740865'});
        });
    }
    receiveScanData(data) {
        // this.order = data;
        this.getOrderDetail({orderId: data.orderId, deviceCode: 'ice'}, (res) => {
            console.log(res);
            if(res.statusCode === '200') {
                this.order = data.orderId;
                // 插入数据库
                this.insertDb('iceCream', res.data.orderDetail, res.data.orderDetail.length - 1, true);
                this.getFreeOrder(this.iceCreamIp);
            }
        })
    }
    receive(key, arr, type) {
        console.log(arr);
        // 根据规则 1、3是心跳和状态上报
        switch (type) {
            case 0: 
                // 更新心跳时间
                this.clients[key].isOpen = arr[4];
                this.clients[key].workStatus = arr[5];
                this.clients[key].deviceStatus = arr[6];
                this.clients[key].intakeStatus = arr[7];
                return {
                    isSend: true,
                    content: this.messageResponse(0)
                };
                // 正常应答
                break;
            case 2:
                console.log('可否制作', arr);
                let status = '';
                if(arr[4] === 1) {
                    status = '22';
                } else {
                    status = '999';
                }
                this.postMealAbnormal({
                    storeId: this.storeId,
                    orderId: this.order,
                    productId: this.productId,
                    productStatus: status,
                    orderDetailId: this.orderDetailId
                }, (res) => {
                    if(status === '999') {
                        iceCreamModel.updateOrder({date: this.date, _mealId: this._mealId}, {status: '4'});
                    }
                });
                return {
                    isSend: true,
                    content: this.messageResponse(0)
                };
                break;
            case 3:
                console.log("设备状态更改了：", key);
                this.clients[key].isOpen = arr[4];
                this.clients[key].workStatus = arr[5];
                this.clients[key].deviceStatus = arr[6];
                this.clients[key].intakeStatus = arr[7];
                this.clients[key].errorCode = arr[8];
                let errorCode = this.clients[key].errorCode;
                let isError = false, // 是否异常
                    code = '', //设备状态
                    message = ''; // 异常信息
                // http 及时上报该设备状态
                if(this.clients[key].isOpen === 2) {
                    isError = true;
                    message = '设备未启动';
                } else if (this.clients[key].deviceStatus === 2) {
                    isError = true;
                    message = '设备异常';
                } else if (errorCode !== 0) {
                    errorCode = this.prefixInteger(this.convertBinary(errorCode), 16).split('').reverse();
                    isError = true;
                    if(errorCode[0] === '1') {
                        message = '1号落杯器无杯子';
                    } 
                    if(errorCode[1] === '1') {
                        message = '2号落杯器无杯子';
                    }
                    if(errorCode[2] === '1') {
                        message = '2个落杯器都没有杯子或者增加杯子了，但是未清除故障';
                    }
                    if(errorCode[3] === '1') {
                        message = '雪糕机缺料';
                    }
                    if(errorCode[4] === '1') {
                        message = '雪糕机故障';
                    }
                    if(errorCode[5] === '1') {
                        message = '光栅有障碍物';
                    }
                    if(errorCode[6] === '1') {
                        message = '顾客迟迟未取餐';
                    }
                    if(errorCode[7] === '1') {
                        message = '杯子掉了';
                    }
                    if(errorCode[8] === '1') {
                        message = '雪糕机失联';
                    }
                    if(errorCode[9] === '1') {
                        message = '旋转台步进电机报错';
                    }
                    if(errorCode[10] === '1') {
                        message = '爪子打开后，杯子没有通过门';
                    }
                    if(errorCode[11] === '1') {
                        message = '雪糕机迟迟不出雪糕';
                    }
                }
                if(isError) {
                    this.postAbnormal({storeId: this.storeId, code: 'ice', message: message} , (res) => {
                        console.log(res);
                    });
                }
                // 当取餐口有雪糕并有订单存在时，说明该订单已制餐完成
                if(this.clients[key].workStatus === 1 && this.clients[key].intakeStatus === 2 && this.order) {
                    this.postMealAbnormal({
                        storeId: this.storeId,
                        orderId: this.order,
                        productId: this.productId,
                        productStatus: '58',
                        orderDetailId: this.orderDetailId
                    } , (res) => {
                        console.log('取餐完成');
                        iceCreamModel.updateOrder({date: this.date, _mealId: this._mealId}, {status: '2'});
                    });
                // 当取餐口没雪糕但还是有订单存在，说明该订单已被取走
                } else if (this.clients[key].workStatus === 1 && this.clients[key].intakeStatus === 1 && this.order) {
                    this.postMealAbnormal({
                        storeId: this.storeId,
                        orderId: this.order,
                        productId: this.productId,
                        productStatus: '510',
                        orderDetailId: this.orderDetailId
                    }, (res) => {
                        console.log('已取餐');
                        iceCreamModel.updateOrder({date: this.date, _mealId: this._mealId}, {status: '3'});
                    });
                    this.getFreeOrder(this.iceCreamIp);
                    this.order = '';
                }
                return {
                    isSend: true,
                    content: this.messageResponse(0)
                };
                break;
        }
    }
    getFreeOrder(key) {
        setTimeout(() => {
            let client = this.clients[key];
            if(client.isOpen === 1 && client.workStatus === 1 && client.deviceStatus === 1 && client.intakeStatus === 1) {
                iceCreamModel.findFreeOrder((res) => {
                    let detail = JSON.parse(res.orderDetail);
                    let content = this.messageResponse(170, 2, this.getRandom(), 6, 0, 2, 2);
                    console.log(content);
                    this.tcpSend(key, content);
                    this.order = detail.orderId;
                    this.productId = detail.productId;
                    this.orderDetailId = detail.id;
                    this.device[deviceId].date = res.date;
                    this._mealId = res._mealId;
                })
            }
        }, 1000);
    }
}
module.exports = iceCream;